<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .box {
        width: 100%;
        height: 3000px;
        background-image: linear-gradient(skyblue, pink);
      }

      .rocket {
        width: 148px;
        height: 250px;
        display: none;
        position: fixed;
        bottom: 0;
        right: 0;
        background-image: url(./rocket.png);
      }

      .rocket:hover {
        background-position: -148px 0;
        cursor: pointer;
      }

      .active {
        animation: fire 0.4s steps(4) 0s infinite;
      }

      /* 喷火动画 */
      @keyframes fire {
        from {
          background-position: -296px 0;
        }
        to {
          background-position: -892px 0;
        }
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="rocket"></div>
    </div>
    <script>
      var rocket = document.querySelector('.rocket');
      var rocket_distance; // 火箭的路程
      var rocket_v; // 火箭的速度
      var scroll_distance; // 滚动条的路程
      var scroll_v; // 滚动条的速度
      var timer = null; // 作为判断火箭是否处于飞行状态的标志
      rocket.onclick = function () {
        rocket.classList.add('active'); // 点击后添加喷火的样式
        rocket_distance = rocket.offsetTop + 250;
        rocket_v = rocket_distance / 50;
        scroll_distance = document.documentElement.scrollTop;
        scroll_v = scroll_distance / 50;
        // 在 setInterval 里设置火箭和滚动条的移动
        timer = setInterval(function () {
          rocket.style.top = rocket.offsetTop - rocket_v + 'px'; // 火箭移动
          document.documentElement.scrollTop -= scroll_v; // 滚动条移动
          // 滚动到顶部时移除喷火样式并隐藏火箭
          if (document.documentElement.scrollTop === 0) {
            clearInterval(timer); // 清除定时器
            timer = null;
            rocket.style.top = ''; // 火箭top属性恢复默认值
            rocket.classList.remove('active'); // 移除喷火样式
            rocket.style.display = 'none'; // 隐藏火箭
          }
        }, 20);
      };
      // 监听整个页面的滚动事件，设置火箭在页面被滚动去一定高度时出现
      window.onscroll = function () {
        if (window.scrollY > 800) {
          rocket.style.display = 'block';
        } else {
          rocket.style.display = 'none';
        }
        if (timer) {
          rocket.style.display = 'block'; // 判断火箭正在飞行，使其可见
        }
      };
    </script>
  </body>
</html>
